﻿// /////////////////////////////////// 
//  
//  
//      WiseLink CCF2.0 
//     (c)Copyright 2001-2010 WiseLink Xiaojun (David) Chen 
//        Authored and Owned Xiaojun (David) Chen 
//        All Right Reserved
//  
// /////////////////////////////////// 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZICModel.Common;
using ZIC20Contract.DataType;

namespace ZICModel.Position
{
    public class PositionHandler : ZICBaseModel
    {
        public GPSPositionInfo GetLastKnownGoodPosition(string idc)
        {
            GpsCarCurrentPosInfo posInfo = zic2Entities.GpsCarCurrentPosInfoes.Where(g => g.telephone.Equals(idc, StringComparison.OrdinalIgnoreCase)).OrderByDescending(g => g.gpsTime).FirstOrDefault();
            if (posInfo != null)
            {
                return new GPSPositionInfo { GpsTime = posInfo.gpsTime, Latitude = posInfo.Latitude, Longitude = posInfo.Longitude };
            }
            else
            {
                return null;
            }

        }

        public IEnumerable<GPSPositionInfo> GpsPositionTrace(string idc, DateTime startTime, DateTime endTime)
        {
            // check table 
            var query1=  from g in zic2Entities.gpsrecerealtime_buff1
                        where g.telephone.Equals(idc, StringComparison.OrdinalIgnoreCase)&& g.gpstime > startTime && g.gpstime < endTime
                        orderby g.gpstime descending
                        select new GPSPositionInfo { GpsTime = g.gpstime, Latitude = g.Latitude, Longitude = g.Longitude };
            
            var query2 = from g in zic2Entities.gpsrecerealtime_buff2
                         where g.telephone.Equals(idc, StringComparison.OrdinalIgnoreCase) && g.gpstime > startTime && g.gpstime < endTime
                         orderby g.gpstime descending
                         select new GPSPositionInfo { GpsTime = g.gpstime, Latitude = g.Latitude, Longitude = g.Longitude };
            
            var query3 = query1.Concat(query2);

            if (query3.Count() > 0)
            {
                return query3;
            }
            else
            {
                //GpsReceRealTimes is the history table (have all the data so it is big.)
               return   from g in zic2Entities.GpsReceRealTimes
                         where g.telephone.Equals(idc, StringComparison.OrdinalIgnoreCase) && g.gpstime > startTime && g.gpstime < endTime
                         orderby g.gpstime descending
                         select new GPSPositionInfo { GpsTime = g.gpstime, Latitude = g.Latitude, Longitude = g.Longitude };
            }

        }
    }
}
